(function ($) {
	
	
    $.util.namespace("mainpage.nav");
    $.util.namespace("mainpage.mainTabs");
    $.util.namespace("mainpage.user");

    
    
    var homePageTitle = "主页", homePageHref = null, navMenuList = "#navMenu_list",
    	westCenterLayoutPanel = "#westCenterLayoutPanel", navMenuTree = "#navMenu_Tree", mainTabs = "#mainTabs", navTabs = "#navTabs",
        mainLayout = "#mainLayout", northPanel = "#northPanel", themeSelector = "#themeSelector",
        westLayout = "#westLayout", westCenterLayout = "#westCenterLayout",
        westSouthPanel = "#westSouthPanel", btnFullScreen = "#btnFullScreen";

    
    // 按照指定的根节点菜单 id，加载其相应的子菜单树面板数据；该方法定义如下参数：
    // id: 表示根节点菜单的 id；
    window.mainpage.loadMenu = function (id) {
    	window.mainpage.instNavTree();
    	$.easyui.loading({ locale: westCenterLayout });
    	var t = $(navMenuTree), root = $.extend({}, $.array.first(window.mainpage.navMenusData, function (val) { return val.id == id; }));
		$.get($.ctx+"/manager/system/menu/getAllMenusViewChildren/"+id, function (menus) {
			root.iconCls = "icon-standard-application-view-list";
			root.children = $.array.likeArrayNotString(menus) ? menus : [];
			t.tree("loadData", [root]);
		}, "json");
    };
    

    // 将指定的根节点数据集合数据加载至左侧面板中“导航菜单”的 ul 控件中；该方法定义如下参数：
    // callback:  为一个 Function 对象；表示家在完成菜单数据后调用的回调函数
    window.mainpage.loadNavMenus = function (callback) {
        var ul = $(navMenuList).empty();
        $.get($.ctx+"/manager/system/menu/getAllMenusViewCatalog", function (menus) {
            $.each(window.mainpage.navMenusData = menus = $.array.filter(menus, function (item) {
                return item.status ? false : true;
            }), function (i, item) {
                var li = $("<li></li>").appendTo(ul);
                var pp = $("<div></div>").addClass("panel-header panel-header-noborder").appendTo(li);
                var a = $("<a></a>").attr({ href: "javascript:void(0);", target: "_self" }).css("color", item.color?item.color:"").hover(function () {
                    a.addClass("tree-node-selected");
                }, function () {
                    if (!a.hasClass("selected")) { $(this).removeClass("tree-node-selected"); }
                }).click(function () {
                    if (a.is(".tree-node-selected.selected") || a.attr("disabled")) { return; }
                    ul.find("a").removeClass("tree-node-selected selected");
                    a.addClass("tree-node-selected selected");
                    
                    window.mainpage.loadMenu(item.id);
                    
                }).appendTo(pp);
                $.data(a[0], "menu-item", item);
                $("<span class=\"l-btn-left l-btn-icon-left\">" + 
                		"<span class=\"menuContainer\">" +
                		"<i class=\"fa "+(item.iconCls?item.iconCls:"fa-viacoin")+" fa-120\"></i><span class='text'>" + item.text + "</span></span>" +
                        "</span></span>").appendTo(a);
            });
            var layout = $(westLayout),
                south = layout.layout("panel", "south"),
                southOpts = south.panel("options"),
                border = south.panel("panel").border("top"),
                navHeight = 27;
            southOpts.minHeight = border + Math.min(menus.length, 3) * navHeight;
            southOpts.maxHeight = border + menus.length * navHeight;
            layout.layout("resize");
            if ($.isFunction(callback)) { callback.call(ul, menus); }
        }, "json");
    };

    window.mainpage.instTreeStatus = function (target) {
        var t = $(target), array = t.tree("getRoots");
        $.each(array, function (i, n) {
            var cc = t.tree("getChildren", n.target);
            t.tree("expand", n.target);
            $.each(cc, function (l, c) { t.tree("collapseAll", c.target); });
        });
    };

    //初始化 westSouthPanel 位置的“导航菜单”区域子菜单 ul 控件(仅初始化 easyui-tree 对象，不加载数据)。
    window.mainpage.instNavTree = function () {
    	var nd = $(westCenterLayoutPanel).empty() ;
    	var t = $("<ul></ul>").attr("id", "navMenu_Tree").appendTo(nd);
        if (t.isEasyUI("tree")) { return; }
        t.tree({
            animate: true,
            lines: true,
            toggleOnClick: true,
            selectOnContextMenu: true,
            onClick: function (node) {
            	//判断是否加上ctx，如果没有则加上。
            	if(undefined != node.attributes) {
            		var href = node.attributes.href ;
            		if(undefined != href && "" != href.trim()){
            			if(href.indexOf($.ctx) == -1) {
            				node.attributes.href=$.ctx+href ;
            			}
            		}
            	} else {
            		var href = node.href ;
            		if(undefined != href && "" != href.trim()){
            			if(href.indexOf($.ctx) == -1) {
            				node["attributes"] = {"href": $.ctx+href};
            			}
            		}
            	}
                window.mainpage.addModuleTab(node);
            },
            onLoadSuccess: function (node, data) {
                $(navMenuList).find("a").removeAttr("disabled");
                window.mainpage.instTreeStatus(t);
                $.easyui.loaded(westCenterLayout);
            }
        });
    };

    //  初始化应用程序主界面左侧面板中“导航菜单”的数据，并加载特定的子菜单树数据。
    window.mainpage.instMainMenus = function () {
        window.mainpage.loadNavMenus(function () {
            if (window.mainpage.navMenusData.length) {
                var list = $(navMenuList).find("a");
                if (!list.length) { return; }
                var menu = list.filter(function () { var item = $.data(this, "menu-item"); return item.defaultSelect; }),
                    target = menu.length ? menu : list.eq(0);
                target.click();
            }
        });
    };





    window.mainpage.instTimerSpan = function () {
        var timerSpan = $("#timerSpan"), interval = function () { timerSpan.text($.date.format(new Date(), "yyyy年MM月dd日 HH:ss:mm")); };
        interval();
        window.setInterval(interval, 1000);
    };

    window.mainpage.bindToolbarButtonEvent = function () {
        $("#btnHideNorth").click(function () { window.mainpage.hideNorth(); });
        
        var btnShow = $("#btnShowNorth").click(function () { window.mainpage.showNorth(); });
        
        var l = $(mainLayout), north = l.layout("panel", "north"), panel = north.panel("panel"),
            toolbar = $("#toolbar"), topbar = $("#topbar");
        
        
        opts = north.panel("options"), onCollapse = opts.onCollapse, onExpand = opts.onExpand;
        opts.onCollapse = function () {
            if ($.isFunction(onCollapse)) { onCollapse.apply(this, arguments); }
            toolbar.show();
            toolbar.insertBefore(panel).addClass("top-toolbar-topmost");
        };
        opts.onExpand = function () {
            if ($.isFunction(onExpand)) { onExpand.apply(this, arguments); }
            toolbar.hide();
            toolbar.insertAfter(topbar).removeClass("top-toolbar-topmost");
        };

        $(btnFullScreen).click(function () {
            if ($.util.supportsFullScreen) {
                if ($.util.isFullScreen()) {
                    $.util.cancelFullScreen();
                } else {
                    $.util.requestFullScreen();
                }
            } else {
                $.easyui.messager.show("当前浏览器不支持全屏 API，请更换至最新的 Chrome/Firefox/Safari 浏览器或通过 F11 快捷键进行操作。");
            }
        });

        
    };
    
    window.mainpage.logout = function() {
    	$.easyui.messager.confirm("操作提醒", "您确定要退出当前程序并关闭该网页？", function (c) {
    		if (c) {
    			$.get($.ctx+"/admin/logout", function() {
    				window.location.replace($.ctx+"/admin/login");
    			});
    		}
    	});
    };


    window.mainpage.bindMainTabsButtonEvent = function () {
        $("#mainTabs_jumpHome").click(function () { window.mainpage.mainTabs.jumpHome(); });
        $("#mainTabs_toggleAll").click(function () { window.mainpage.togglePanels(); });
        $("#mainTabs_jumpTab").click(function () { window.mainpage.mainTabs.jumpTab(); });
        $("#mainTabs_closeTab").click(function () { window.mainpage.mainTabs.closeCurrentTab(); });
        $("#mainTabs_closeOther").click(function () { window.mainpage.mainTabs.closeOtherTabs(); });
        $("#mainTabs_closeLeft").click(function () { window.mainpage.mainTabs.closeLeftTabs(); });
        $("#mainTabs_closeRight").click(function () { window.mainpage.mainTabs.closeRightTabs(); });
        $("#mainTabs_closeAll").click(function () { window.mainpage.mainTabs.closeAllTabs(); });
    };

    window.mainpage.bindNavTabsButtonEvent = function () {
        $("#navMenu_refresh").click(function () { window.mainpage.refreshNavTab(); });

        $("#navMenu_Rename").click(function () { window.mainpage.nav.rename(); });
        $("#navMenu_expand").click(function () { window.mainpage.nav.expand(); });
        $("#navMenu_collapse").click(function () { window.mainpage.nav.collapse(); });
        $("#navMenu_collapseCurrentAll").click(function () { window.mainpage.nav.expandCurrentAll(); });
        $("#navMenu_expandCurrentAll").click(function () { window.mainpage.nav.collapseCurrentAll(); });
        $("#navMenu_collapseAll").click(function () { window.mainpage.nav.expandAll(); });
        $("#navMenu_expandAll").click(function () { window.mainpage.nav.collapseAll(); });
        
        
        $("#btoHideWest").click(function () { window.mainpage.hideWest(); });
        $("#btoHideEast").click(function () { window.mainpage.hideEast(); });
        
        $("#main-info").click(function () { window.mainpage.user.info(); });
        $("#main-changePassword").click(function () { window.mainpage.user.changePassword(); });
        $("#main-record").click(function () { window.mainpage.user.printRecord(); });
        $("#main-sendmail").click(function () { window.mainpage.user.sendMail(); });
        $("#logoutSystem").click(function () { window.mainpage.logout(); });
    };

    window.mainpage.hideNorth = function () { $(mainLayout).layout("collapse", "north"); };
    window.mainpage.showNorth = function () { $(mainLayout).layout("expand", "north"); };
    window.mainpage.hideWest = function () { $(mainLayout).layout("collapse", "west"); };
    window.mainpage.hideEast = function () { $(mainLayout).layout("collapse", "east"); };

    window.mainpage.togglePanels = function () { $(mainLayout).layout("toggleAll", "collapse"); };

    window.mainpage.addModuleTab = function (node) {
        var n = node || {}, attrs = node.attributes || {}, opts = $.extend({}, n, { title: n.text }, attrs);
        if (!opts.href) { return; }
        window.mainpage.mainTabs.addModule(opts);
    };

    //  判断指定的选项卡是否存在于当前主页面的选项卡组中；
    //  返回值：返回的值可能是以下几种：
    //      0:  表示不存在于当前选项卡组中；
    //      1:  表示仅 title 值存在于当前选项卡组中；
    //      2:  表示 title 和 href 都存在于当前选项卡组中；
    window.mainpage.mainTabs.isExists = function (title, href) {
        var t = $(mainTabs), tabs = t.tabs("tabs"), array = $.array.map(tabs, function (val) { return val.panel("options"); }),
            list = $.array.filter(array, function (val) { return val.title == title; }), ret = list.length ? 1 : 0;
        if (ret && $.array.some(list, function (val) { return val.href == href; })) { ret = 2; }
        return ret;
    };

    window.mainpage.mainTabs.tabDefaultOption = {
        title: "新建选项卡", href: "", iniframe: true, closable: true, refreshable: true, iconCls: "icon-standard-application-form", repeatable: true, selected: true
    };
    window.mainpage.mainTabs.parseCreateTabArgs = function (args) {
        var ret = {};
        if (!args || !args.length) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption);
        } else if (args.length == 1) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, typeof args[0] == "object" ? args[0] : { href: args[0] });
        } else if (args.length == 2) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1] });
        } else if (args.length == 3) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2] });
        } else if (args.length == 4) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3] });
        } else if (args.length == 5) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4] });
        } else if (args.length == 6) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4], refreshable: args[5] });
        } else if (args.length >= 7) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4], refreshable: args[5], selected: args[6] });
        }
        return ret;
    };

    window.mainpage.mainTabs.createTab = function (title, href, iconCls, iniframe, closable, refreshable, selected) {
        var t = $(mainTabs), i = 0, opts = window.mainpage.mainTabs.parseCreateTabArgs(arguments);
        while (t.tabs("getTab", opts.title + (i ? String(i) : ""))) { i++; }
        opts.icon="";
        t.tabs("add", opts);
    };

    //  添加一个新的模块选项卡；该方法重载方式如下：
    //      function (tabOption)
    //      function (href)
    //      function (title, href)
    //      function (title, href, iconCls)
    //      function (title, href, iconCls, iniframe)
    //      function (title, href, iconCls, iniframe, closable)
    //      function (title, href, iconCls, iniframe, closable, refreshable)
    //      function (title, href, iconCls, iniframe, closable, refreshable, selected)
    window.mainpage.mainTabs.addModule = function (title, href, iconCls, iniframe, closable, refreshable, selected) {
        var opts = window.mainpage.mainTabs.parseCreateTabArgs(arguments), isExists = window.mainpage.mainTabs.isExists(opts.title, opts.href);
        switch (isExists) {
            case 0: window.mainpage.mainTabs.createTab(opts); break;
            case 1: window.mainpage.mainTabs.createTab(opts); break;
            case 2: window.mainpage.mainTabs.jumeTab(opts.title); break;
            default: break;
        }
    };

    window.mainpage.mainTabs.jumeTab = function (which) { $(mainTabs).tabs("select", which); };

    window.mainpage.mainTabs.jumpHome = function () {
        var t = $(mainTabs), tabs = t.tabs("tabs"), panel = $.array.first(tabs, function (val) {
            var opts = val.panel("options");
            return opts.title == homePageTitle && opts.href == homePageHref;
        });
        if (panel && panel.length) {
            var index = t.tabs("getTabIndex", panel);
            t.tabs("select", index);
        }
    };

    window.mainpage.mainTabs.jumpTab = function (which) { $(mainTabs).tabs("jumpTab", which); };

    window.mainpage.mainTabs.closeTab = function (which) { $(mainTabs).tabs("close", which); };

    window.mainpage.mainTabs.closeCurrentTab = function () {
        var t = $(mainTabs), index = t.tabs("getSelectedIndex");
        return t.tabs("closeClosable", index);
    };

    window.mainpage.mainTabs.closeOtherTabs = function (index) {
        var t = $(mainTabs);
        if (index == null || index == undefined) { index = t.tabs("getSelectedIndex"); }
        return t.tabs("closeOtherClosable", index);
    };

    window.mainpage.mainTabs.closeLeftTabs = function (index) {
        var t = $(mainTabs);
        if (index == null || index == undefined) { index = t.tabs("getSelectedIndex"); }
        return t.tabs("closeLeftClosable", index);
    };

    window.mainpage.mainTabs.closeRightTabs = function (index) {
        var t = $(mainTabs);
        if (index == null || index == undefined) { index = t.tabs("getSelectedIndex"); }
        return t.tabs("closeRightClosable", index);
    };

    window.mainpage.mainTabs.closeAllTabs = function () {
        return $(mainTabs).tabs("closeAllClosable");
    };

    window.mainpage.mainTabs.updateHash = function (index) {
        var opts = $(mainTabs).tabs("getTab", index).panel("options");
        window.location.hash = opts.href ? opts.href : "";
        $("link#favicon").attr("href", $.ctx+"/static/imgs/favicon.ico") ;
    };

    window.mainpage.mainTabs.loadHash = function (hash) {
    	while (hash.left(1) == "#") { hash = hash.substr(1); }
    	var href = hash.replace($.ctx, "") ;
    	//根据href查询数据获取node
        
        if (String.isNullOrWhiteSpace(hash)) { return; }
        $.get($.ctx+"/manager/system/menu/getLocation?location="+href, function (menu) {
        	var href = menu.location ;
    		if(undefined != href && "" != href.trim()){
    			if(href.indexOf($.ctx) == -1) {
    				menu.href=$.ctx+href ;
    			}
    		}
            if (menu) {
                window.mainpage.addModuleTab(menu);
            } else {
                $.easyui.messager.show("hash is not exists");
            }
        }, "json");
    };


    window.mainpage.refreshNavTab = function (index) {
        var t = $(navTabs);
        if (index == null || index == undefined) { index = t.tabs("getSelectedIndex"); }
        if (index == 0) {
            window.mainpage.nav.refreshNav();
        } 
    };




    window.mainpage.nav.refreshNav = function () { window.mainpage.instMainMenus(); };

    window.mainpage.nav.refreshTree = function () {
        var menu = $(navMenuList).find("a.tree-node-selected.selected"), item = $.data(menu[0], "menu-item");
        if (item && item.id) { window.mainpage.loadMenu(item.id); }
    };



    window.mainpage.nav.expand = function (id) {
        var t = $(navMenuTree), node;
        if (id == null || id == undefined) {
            node = t.tree("getSelected");
            if (!node) { return $.easyui.messager.show("请先选择一行数据"); }
        } else {
            node = t.tree("find", id);
            if (!node) { return $.easyui.messager.show("请传入有效的参数 id(菜单标识号)"); }
        }
        t.tree("expand", node.target);
    };

    window.mainpage.nav.collapse = function (id) {
        var t = $(navMenuTree), node;
        if (id == null || id == undefined) {
            node = t.tree("getSelected");
            if (!node) { return $.easyui.messager.show("请先选择一行数据"); }
        } else {
            node = t.tree("find", id);
            if (!node) { return $.easyui.messager.show("请传入有效的参数 id(菜单标识号)"); }
        }
        t.tree("collapse", node.target);
    };

    window.mainpage.nav.expandCurrentAll = function (id) {
        var t = $(navMenuTree), node;
        if (id == null || id == undefined) {
            node = t.tree("getSelected");
            if (!node) { return $.easyui.messager.show("请先选择一行数据"); }
        } else {
            node = t.tree("find", id);
            if (!node) { return $.easyui.messager.show("请传入有效的参数 id(菜单标识号)"); }
        }
        t.tree("expandAll", node.target);
    };

    window.mainpage.nav.collapseCurrentAll = function (id) {
        var t = $(navMenuTree), node;
        if (id == null || id == undefined) {
            node = t.tree("getSelected");
            if (!node) { return $.easyui.messager.show("请先选择一行数据"); }
        } else {
            node = t.tree("find", id);
            if (!node) { return $.easyui.messager.show("请传入有效的参数 id(菜单标识号)"); }
        }
        t.tree("collapseAll", node.target);
    };

    window.mainpage.nav.expandAll = function () { $(navMenuTree).tree("expandAll"); };

    window.mainpage.nav.collapseAll = function () { $(navMenuTree).tree("collapseAll"); };




    
    
    //初始化友情链接列表
    $.util.namespace("link");
    window.link.reload = function () {
    	
    };
    
    
    /**
     * 我的信息
     */
    window.mainpage.user.info = function() {
    	var $d = $.easyui.showDialog({
			title: "<div class='icon-div'><i class='fa fa-link fa-120 pt-2 fa-c-blue'></i></div> 我的信息", 
			href: $.ctx+"/manager/myInfoDialog", method: "", 
			iniframe: false, topMost: true, iconCls : "",
			width: 610, height: 344, maximizable: true,
            enableApplyButton: false, enableCloseButton: false, enableSaveButton: false,
            buttons : [ 
              { text : "<i class='fa fa-remove fa-120 mt-6 fa-c-red'></i> 关闭", handler : function() { $d.dialog('destroy'); } } 
           	]
        });
    };
    /**
     * 修改密码
     */
    window.mainpage.user.changePassword = function() {
    	var $d = $.easyui.showDialog({
			title: "<div class='icon-div'><i class='fa fa-link fa-120 pt-2 fa-c-blue'></i></div> 修改密码", 
			href: $.ctx+"/manager/changePasswordDialog", method: "", 
			iniframe: false, topMost: true, iconCls : "",
			width: 410, height: 200, maximizable: true,
            enableApplyButton: false, enableCloseButton: false, enableSaveButton: false,
            buttons : [ 
              { text : "<i class='fa fa-save fa-120 mt-6 fa-c-blue'></i> 修改", handler : function() { $.easyui.parent.submitForm($d) ; } },
              { text : "<i class='fa fa-remove fa-120 mt-6 fa-c-red'></i> 关闭", handler : function() { $d.dialog('destroy'); } } 
           	]
        });
    };
    /**
     * 打印我的信息
     */
    window.mainpage.user.printRecord = function() {
    	var $d = $.easyui.showDialog({
			title: "<div class='icon-div'><i class='fa fa-link fa-120 pt-2 fa-c-blue'></i></div> 履历信息", 
			href: $.ctx+"/manager/printRecord", method: "", 
			iniframe: false, topMost: true, iconCls : "",
			width: 610, height: 344, maximizable: true,
            enableApplyButton: false, enableCloseButton: false, enableSaveButton: false,
            buttons : [ 
              { text : "<i class='fa fa-save fa-120 mt-6 fa-c-blue'></i> 修改", handler : function() { $.easyui.parent.submitForm($d) ; } },
              { text : "<i class='fa fa-remove fa-120 mt-6 fa-c-red'></i> 关闭", handler : function() { $d.dialog('destroy'); } } 
           	]
        });
    };
    /**
     * 发送邮件
     */
    window.mainpage.user.sendMail = function() {
    	var $d = $.easyui.showDialog({
			title: "<div class='icon-div'><i class='fa fa-link fa-120 pt-2 fa-c-blue'></i></div> 发送邮件", 
			href: $.ctx+"/manager/sendMailDialog", method: "", 
			iniframe: false, topMost: true, iconCls : "",
			width: 610, height: 344, maximizable: true,
            enableApplyButton: false, enableCloseButton: false, enableSaveButton: false,
            buttons : [ 
              { text : "<i class='fa fa-save fa-120 mt-6 fa-c-blue'></i> 修改", handler : function() { $.easyui.parent.submitForm($d) ; } },
              { text : "<i class='fa fa-remove fa-120 mt-6 fa-c-red'></i> 关闭", handler : function() { $d.dialog('destroy'); } } 
           	]
        });
    };



})(jQuery);